package com.Xht.www.servlet;

//后端响应收藏商家的请求

import com.Xht.www.dao.UserFavoritesDAO;
import com.Xht.www.po.UserFavoritesPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

@WebServlet("/favorite-merchant")
public class FavoriteMerchantServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 获取参数
        String userIdParam = request.getParameter("userId");
        String merchantName = request.getParameter("merchantName");
        String favoriteReason = request.getParameter("favoriteReason");

        // 验证参数
        if (userIdParam == null || merchantName == null || favoriteReason == null ||
                userIdParam.isEmpty() || merchantName.isEmpty() || favoriteReason.isEmpty()) {
            response.getWriter().write("{\"success\": false, \"message\": \"参数不能为空\"}");
            return;
        }

        try {
            // 转换用户ID为整数
            int userId = Integer.parseInt(userIdParam);

            // 创建收藏对象
            UserFavoritesPO favorite = new UserFavoritesPO();
            favorite.setUserId(userId);
            favorite.setMerchantName(merchantName);
            favorite.setFavoriteReason(favoriteReason);
            favorite.setFavoriteTime(new Timestamp(new Date().getTime()));

            // 保存到数据库
            UserFavoritesDAO dao = new UserFavoritesDAO();
            boolean result = dao.insertUserFavorites(favorite);

            if (result) {
                response.getWriter().write("{\"success\": true, \"message\": \"收藏成功\"}");
            } else {
                response.getWriter().write("{\"success\": false, \"message\": \"收藏失败\"}");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("{\"success\": false, \"message\": \"用户ID格式错误\"}");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"success\": false, \"message\": \"服务器内部错误\"}");
        }
    }
}